﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace Utility.BehaviourTree
{
	public abstract class ParallelNode : CompositeNode
	{
		protected Dictionary<BTNode, Status> statusDict = new Dictionary<BTNode, Status> ();

		protected override Status OnUpdate ()
		{
			//update all child nodes
			foreach (var childnode in childNodes)
			{
				if (childnode.IsRunning)
				{
					statusDict[childnode] = childnode.Update ();
				}
			}
			return CheckChildNodeResults ();
		}

		protected abstract Status CheckChildNodeResults ();

		protected override void OnReset ()
		{
			base.OnReset ();
			statusDict.Clear ();
		}
	}

	public class ParalleSequenceNode : ParallelNode
	{
		protected override Status CheckChildNodeResults ()
		{
			int successCount = 0;
			foreach (var child in childNodes)
			{
				switch (statusDict[child])
				{
					case Status.Success:
						successCount++;
						break;
					case Status.Failure:
						return Status.Failure;
					case Status.Error:
						return Status.Error;
				}
			}
			if (successCount == childNodes.Count)
			{
				return Status.Success;
			}
			else
			{
				return Status.Running;
			}
		}
	}

	public class ParralleSelectorNode : ParallelNode
	{
		protected override Status CheckChildNodeResults ()
		{
			int failCount = 0;
			foreach (var child in childNodes)
			{
				switch (statusDict[child])
				{
					case Status.Success:
						return Status.Success;
					case Status.Failure:
						failCount++;
						break;
					case Status.Error:
						return Status.Error;
				}
			}
			if (failCount == childNodes.Count)
			{
				return Status.Failure;
			}
			else
			{
				return Status.Running;
			}
		}
	}
}